* Dickstein, Ho, and Mark (2023)
* This script creates a maptile of MLRs

* Preliminaries
cd ../..
global graph_out = "release/mlr_maps"
shell mkdir -p "$graph_out"
maptile_install using "http://files.michaelstepner.com/geo_statehex.zip"

* Load data
import delimited using "~/sharedWork/oregon/Analysis_QL/orsg_rep/derived/build/cms_mlr/clean_mlr_all_carriers.csv", clear
keep if market == "INDIVIDUAL" | market == "SMALLGROUP"

* Collapse to premiums, claims, and covered lives
gen total_prem = (row_lookup_code == "TOTAL_DIRECT_PREMIUM_EARNED") * value
gen total_cost = (row_lookup_code == "TOTAL_INCURRED_CLAIMS_PT1") * value
gen total_lives = (row_lookup_code == "NUMBER_OF_COVERED_LIVES") * value
collapse (sum) total_prem total_cost total_lives, by(business_state market report_year)
gen medical_markup = total_prem / total_cost
gen state = business_state
gen sg_vs_indiv = (market == "SMALLGROUP")

*Optional: to get the 2017 how many states number:
preserve
drop if medical_markup == .
keep market state report_year medical_markup
keep if report_year == 2017
drop if state == "Grand Total" | state == "VI" | state == "PR" | state == "GU" | state == "DC"
reshape wide medical_markup, i(state ) j(market) string
gen higher_mu_in_sg = (medical_markupSMALLGROUP > medical_markupINDIVIDUAL)
sum higher_mu_in_sg
disp r(sum)
restore

* Writing a program that generates a tile map for a market and state
program drop _all
program define map_mlr_year
    args year market 
    *year - integer market - 1 is sg; 0 o.w.   
    maptile medical_markup if report_year == `year' & sg_vs_indiv == `market', geo(statehex) cutvalues(0 .7 .8 .9 1 1.1 1.2 1.3 1.4 2) fcolor(RdYlBu) savegraph("$graph_out/markup_map_`market'_`year'.eps") replace legdecimals(1) labelhex(state)
end

* Run this program for all years and markets
map_mlr_year 2014 0
map_mlr_year 2015 0
map_mlr_year 2016 0
map_mlr_year 2017 0
map_mlr_year 2014 1
map_mlr_year 2015 1
map_mlr_year 2016 1
map_mlr_year 2017 1